package org.ithang.tools.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        setContext(applicationContext);
    }

    public static void setContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 适用于springBean使用注解@Service("xxxService")
     * 获取接口对象 参数传入xxxService
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }


    /**
     *
     * @param claz
     * @return
     */
    public static <T>T getBean(Class<T> claz){
        return applicationContext.getBean(claz);
    }
    
    public static String getActiveProfile() {
        Environment env = getApplicationContext().getEnvironment();
        String[] activeProfiles = env.getActiveProfiles();
        if (activeProfiles.length > 0) {
            return activeProfiles[0]; // 返回第一个激活的 Profile
        } else {
            return env.getDefaultProfiles()[0]; // 返回默认的 Profile
        }
    }

}
